﻿/*
Latex模块
*/
(function () {
    //备用接口
    var imgUrlBegins = [
          'http://latex.tusuo100.com/api/Latex/tex?latex='
        , 'http://tstest.pptzb.com/api/Latex/tex?latex='

               , 'http://latex.codecogs.com/gif.latex?'
               , 'http://latex.numberempire.com/render?'
    ];
    var imgUrlBeginIndex = 0;
    var imgUrlBegin = imgUrlBegins[imgUrlBeginIndex];

    var $btnMenu = $('.ee-menu-palette-cell');
    var $menus = $('.ee-palette');

    var html2Img = function () {
        var t = $('.ee-tex').val().trim();
        t = encodeURIComponent(t);
        $('.ee-preview-container img').attr('src', imgUrlBegin + t).attr('title', t).attr('alt', t).addClass('is-latex');

        if (t == '') {
            $('.ee-preview-container img').hide();
        } else {
            $('.ee-preview-container img').show();
        }
    };
    //公式代码
    var list0 = "\\alpha \\beta \\gamma \\delta \\epsilon \\varepsilon \\zeta \\eta \\theta \\vartheta \\iota \\kappa \\lambda \\mu \\nu \\xi \\pi \\varpi \\rho \\varrho \\sigma \\varsigma \\tau \\upsilon \\phi \\varphi \\chi \\psi \\omega \\Gamma \\Delta \\Theta \\Lambda \\Xi \\Pi \\Sigma \\Upsilon \\Phi \\Psi \\Omega".split(" ");
    var list1 = "\\times \\div \\cdot \\pm \\mp \\ast \\star \\circ \\bullet \\oplus \\ominus \\oslash \\otimes \\odot \\dagger \\ddagger \\vee \\wedge \\cap \\cup \\aleph \\Re \\Im \\top \\bot \\infty \\partial \\forall \\exists \\neg \\angle \\triangle \\diamond".split(" ");
    var list2 = "\\leq \\geq \\prec \\succ \\preceq \\succeq \\ll \\gg \\equiv \\sim \\simeq \\asymp \\approx \\ne \\subset \\supset \\subseteq \\supseteq \\in \\ni \\notin".split(" ");
    var list3 = "x_{a};x^{b};x_{a}^{b};\\bar{x};\\tilde{x};\\frac{a}{b};\\sqrt{x};\\sqrt[n]{x};\\bigcap_{a}^{b};\\bigcup_{a}^{b};\\prod_{a}^{b};\\coprod_{a}^{b};\\left( x \\right);\\left[ x \\right];\\left\\{ x \\right\\};\\left| x \\right|;\\int_{a}^{b};\\oint_{a}^{b};\\sum_{a}^{b}{x};\\lim_{a \\rightarrow b}{x}".split(";");
    var list4 = "\\leftarrow \\rightarrow \\leftrightarrow \\Leftarrow \\Rightarrow \\Leftrightarrow \\uparrow \\downarrow \\updownarrow \\Uparrow \\Downarrow \\Updownarrow".split(" ");
    var lists = list0.concat(list1).concat(list2).concat(list3).concat(list4);
    var $tables = $('.ee-palette');


    var $items = $('.ee-palette-item');

    var bindEvent = function () {
        $('.ee-preview-container img').bind('error', function () {
            var src = $(this).attr('src');
            var data = '';
            if (src.indexOf('?tex=') > 0) {
                data = src.split('?tex=')[1];
            } else if (src.indexOf('gif.latex?') > 0) {
                data = src.split('gif.latex?')[1];
            } else if (src.indexOf('render?') > 0) {
                data = src.split('render?')[1];
            }
            if (data == '') {
                return;
            }
            imgUrlBeginIndex++;
            console.log(imgUrlBeginIndex)
            if (imgUrlBeginIndex >= imgUrlBegins.length) {
                $('.ee-preview-container img').unbind('error');
                return;
            }
            imgUrlBegin = imgUrlBegins[imgUrlBeginIndex];
            $('.ee-preview-container img').attr('src', imgUrlBegin + data).attr('title', data).attr('alt', data).addClass('is-latex');
            if (data == '') {
                $('.ee-preview-container img').hide();
            } else {
                $('.ee-preview-container img').show();
            }
        });

        $('.ee-menu-palette-body').delegate('.ee-menu-palette-cell', 'click', function () {
            var index = $btnMenu.index(this);
            $menus.hide().eq(index).show();
        });

        $('body').delegate('.ee-palette-item', 'click', function () {
            var index = $items.index(this);
            var v = $('.ee-tex').val();
            $('.ee-tex').val(v + ' ' + lists[index]);
            $('.ee-palette').hide();
            html2Img();
        });
        $('.ee-tex').bind('input', function () {
            html2Img();

        });

        $('.btn-insert').bind('click', function () {
            var t = $('.ee-preview-container img').attr('title') || '';
            var html = $('.ee-preview-container').html().trim();
            if (t == '') {
                html = ' ';
            }
            $('.modal-dialog-content').hide();
            ue.execCommand('inserthtml', html);
            return false;
        });
        $('.btn-cancel').bind('click', function () {
            $('.modal-dialog-content').hide();
            try {
                var h = ue.selection.getRange().getClosedNode().outerHTML;
                ue.execCommand('inserthtml', h);
            } catch (ee) { }
            //11111/ue.execCommand('inserthtml', html);
            return false;
        });
    };
    bindEvent();

    window.openLatexEditor = function (initHtml) {
        initHtml = initHtml || '';
        initHtml = initHtml.replace(/\+/ig, '%20');
        initHtml = decodeURIComponent(initHtml);
        $('.modal-dialog-content').show();
        $('.ee-tex').val(initHtml).trigger('input');
    };
})();

/*题目编辑器模块*/
(function () {
    window.guid = function () {
        var S4 = function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        };
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    var Model = {
        Qestion: {
            Code: guid()
            , QuestionType: "1"
            , QuestionEM: "ABCD"
            , SubjectId: "1"
            , Score: 0
            , Text: "题目"
            , QuestionAnswer: ""
            , QuestionAnalysis: ""
            , Area: ""
            , Arts: ""
            , Tag: ""
            , Year: ""
            , AnswerListJSON: ""
            , ParentId: ""
            , Id: ""
            , LicenseId: ""
            , CorrectAnswer: ""
            , No: ""
            , IsChooseTodo: ""
            , TestType: ""

        }
        , Answer: {
            ID: guid()
            , Answer: ""
        }
        , getFromForm: function () {
            var _this = this;
            _this.Qestion.ParentId = $('#ParentId').val();
            _this.Qestion.Id = $('#Id').val();
            _this.Qestion.LicenseId = $('#LicenseId').val();

            _this.Qestion.QuestionType = $('#QuestionType').val();
            _this.Qestion.QuestionEM = $('#QuestionEM').val();
            _this.Qestion.SubjectId = $('#SubjectId').val();
            _this.Qestion.Score = $('#Score').val();
            _this.Qestion.Area = $('#Area').val();
            _this.Qestion.Arts = $('#Arts').val();
            _this.Qestion.Tag = $('#Tag').val();
            _this.Qestion.Year = $('#Year').val();
            _this.Qestion.TestType = $('#TestType').val();
            _this.Qestion.No = $('#No').val();
            _this.Qestion.IsChooseTodo = $('#IsChooseTodo').is(":checked");

            _this.Qestion.Text = $('#QuestionTitle').html().trim();
            _this.Qestion.QuestionAnswer = $('#QuestionAnswer').html().trim();
            _this.Qestion.QuestionAnalysis = $('#QuestionAnalysis').html().trim();


            var anserList = [];
            var $li = $('.question-options-wrap li');
            $li.each(function (i, item) {
                anserList.push({
                    ID: $(item).attr('data-id')
                    , Content: $(item).find('.editor-item').html().trim()
                    , IsRight: $(item).find('input:checked').length > 0
                });
            });
            _this.Qestion.AnswerListJSON = JSON.stringify(anserList);
            var correctList = [];
            var $correct = $('.question-options-wrap input:checked');
            $correct.each(function (i, item) {
                correctList.push($(item).parent().parent().attr('data-id'));
            });
            _this.Qestion.CorrectAnswer = correctList.join(',');
            return _this.Qestion;
        }
    }
    var key = $("#Code").val();
    var managerUrl = "/Common/Attachment/ReadForEditor?TypeKey=Common_EditorImage&Key=" + key;
    var imageUploadUrl = "/Common/Attachment/UploadForEditor?TypeKey=Common_EditorImage&Key=" + key;
    var fileUploadUrl = "/Common/Attachment/UploadForEditor?TypeKey=Common_EditorFile&Key=" + key;
    var audioUploadUrl = "/Common/Attachment/UploadForEditor?TypeKey=Common_EditorAudio&Key=" + key;
    var videoUploadUrl = "/Common/Attachment/UploadForEditor?TypeKey=Common_EditorVideo&Key=" + key;

    //实例化编辑器
    window.ue = UE.getEditor('editor', {
        fileUrl: fileUploadUrl + "&Category=File",
        audioUrl: audioUploadUrl + "&Category=File",
        videoUrl: videoUploadUrl + "&Category=File",
        imageManagerUrl: managerUrl,
        imageUrl: imageUploadUrl + "&Category=File",
        wordImageUrl: imageUploadUrl + "&Category=File",
        scrawlUrl: imageUploadUrl + "&Category=Scrawl",
        catcherUrl: imageUploadUrl + "&Category=Catch",

        //初始化编辑器的内容
        initialContent: ''
        //编辑区高度
        , initialFrameHeight: 400
        //编辑区宽度
        , initialFrameWidth: 600
        //统计字数
        , wordCount: false
        //显示节点路径
        , elementPathEnabled: false
        //默认focus
        , focus: true
          , toolbars: [
            ['fullscreen', 'source', '|', 'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', '|',
             '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',

                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'pagebreak', 'template', 'background', '|',
                'horizontal', 'spechars', 'snapscreen', 'wordimage', '|',
                'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols'
            ]
          ]
    });


    var $dom = null;

    var showEditor = function () {

        $('#editor').show();
        if ($dom) {
            var html = $dom.html().trim();
            ue.setContent(html);
            ue.focus();
        }
    };

    var hideEditor = function () {
        $('#editor').hide();
        if ($dom) {
            var html = ue.getContent().trim();
            $dom.html(html);
        }
    };

    var initAnswerEM = function () {
        var type = $('#QuestionType').val();
        if (type == 1 || type == 2 || type == 7) {
            var type = $('.question-option-em').val();
            var TypeList = {
                "ABCD": 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W'.split(','),
                "1234": '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20'.split(',')
            }
            var $em = $('.question-options-wrap>li>em');
            $em.each(function (i, item) {
                $em.eq(i).html(TypeList[type][i] + '.');
            });
        }
    }
    var initAnserB = function (onlyLast) {
        onlyLast = !!onlyLast;
        var type = $('#QuestionType').val();
        var html = '';
        if (type == 1 || type == 3) {
            html = '<input type="radio" name="q20160814" />';
        } else if (type == 2 || type == 7) {
            html = '<input type="checkbox" name="q20160814" />';
        }
        var $em = $('.question-options-wrap>li>b');
        if (!onlyLast) {
            console.log($em)
            $em.each(function (i, item) {
                $em.eq(i).html(html);
            });
        } else {
            $('.question-options-wrap>li>b:last').html(html);
        }
    }
    var bindEvent = function () {

        $('.question-editor-wrap').bind('click', function (e) {
            var $o = $(e.target);
            var $p = $o.parents('.editor-item');
            if ($p.length == 0) {
                hideEditor();
            }
        });
        $('body').delegate('.editor-item', 'click', function () {
            if ($dom) {
                var html = ue.getContent().trim();
                $dom.html(html);
            }
            $dom = $(this);
            showEditor();

            return false;
        });

        $('.question-option-em').bind('change', function () {
            initAnswerEM();
        });

        $('#QuestionType').bind('change', function () {
            var type = this.value;
            if (type == 1 || type == 2 || type == 3 || type == 7) {
                $('#question-options').show();
                $('#question-answer').hide();
                if (type == 3) {
                    $('.question-options-wrap').addClass('type-4').html('<li><b><input type="radio" name="q20160814"></b><em>对</em><div class="editor-item"  >对</div><i>移除</i></li><li><b><input type="radio" name="q20160814"></b><em>错</em><div class="editor-item" >错</div><i>移除</i></li>');
                    $('.btn-add-item').hide();
                } else {
                    $('.question-options-wrap').removeClass('type-4');
                    $('.btn-add-item').show();
                }
            } else {
                $('#question-options').hide();
                if (type == 6) {
                    $('#question-answer').hide();
                } else {
                    $('#question-answer').show();
                }
            }
            initAnserB();
            initAnswerEM();
        });
        $('#question-options').delegate('.btn-add-item', 'click', function () {
            var $ul = $('.question-options-wrap');
            var $li = $('<li data-id="' + guid() + '"><b></b><em></em><div class="editor-item">新选项</div><i>移除</i></li>').appendTo($ul);
            $li.find('.editor-item').trigger('click');
            initAnswerEM();
            initAnserB(true);

        });
        $('#question-options ul').delegate('i', 'click', function () {
            if (!confirm('确认移除?')) {
                return false;
            }
            $(this).parent().remove();
            initAnswerEM();
        });
        //公式编辑器入口
        setTimeout(function () {
            $('#edui2').append('<a href="javascript:;" onclick="openLatexEditor();">插入公式</a>');
            //$('.modal-dialog-content').appendTo($('#edui2'));
            $('#edui2').css('overflow', 'visible');

            $('.modal-dialog-content')[0].onmousedown = function (e) {
                if (e.target.tagName == 'TEXTAREA') {
                    $('.ee-palette').hide();
                    return true;
                }
                return false;
            }


        }, 1000);

        var savaLock = false;
        $('.btn-save').bind('click', function () {
            var result = Model.getFromForm();
            //    console.log(result);
            if (savaLock) {
                return;
            }
            savaLock = true;
            $.ajax
            ({
                url: "/TS/Question/Create",
                data: result,
                type: "post",
                error: disposeError,
                success: function (result) {
                    savaLock = false;
                    if (disposeException(result)) return;
                    alert("保存成功");
                    window.close();
                    //    back(true);
                }
            });
            return false;
        })

        $('#toolbar .i-closetab').parent().bind('click', function () {

            window.close();
            //    back(true);

        })





    };
    bindEvent();
    // $("#QuestionType").trigger("change");

    window.editLatex = function () {
        openLatexEditor(tmpLatexImg)
    }

    $('.top-tab a').eq(0).bind('click', function () {
        $('.top-tab .on').removeClass('on');
        $(this).addClass('on');
        $('.tab-page-0').show();
        $('.tab-page-1').hide();
    });
    $('.top-tab a').eq(1).bind('click', function () {
        $('.top-tab .on').removeClass('on');
        $(this).addClass('on');
        $('.tab-page-1').show();
        $('.tab-page-0').hide();
    });


})();

